package com.rmv.ums.response;

import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.rmv.ums.condition.MethodCondition;

// TODO en vez de sustituir solo los parametros hay que dejar sustituir mas cosas (method,extract things from params,etc)
public class ConfigurationResponse extends AbstractResponse {

	private static final Logger logger = Logger.getLogger(MethodCondition.class);

	public void process(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		if (logger.isDebugEnabled())
			logger.debug("processing response:" + this);

		String response = replaceParameters(req);

		// writing response
		Writer writer = resp.getWriter();
		writer.write(response);
		writer.close();

		logger.info("processed response:" + this.getId());
		logger.info("sent response:" + response);

	}

	private String replaceParameters(HttpServletRequest req) {

		// replacing parameters in response
		String response = getValue();
		Map parameters = req.getParameterMap();

		if (logger.isDebugEnabled())
			logger.debug("replacing parameters (" + parameters.size() + ") on response value");

		for (Iterator iterator = parameters.keySet().iterator(); iterator.hasNext();) {
			String key = (String) iterator.next();
			String param = getParamValue(parameters, key);
			if (StringUtils.isNotBlank(param))
				response = StringUtils.replace(response, "${" + param + "}", param);
		}
		return response;
	}

	private String getParamValue(Map parameters, String key) {
		String param = null;
		Object object = parameters.get(key);
		if (object instanceof String) {
			param = (String) object;
		}
		return param;
	}

}
